package com.moyuaninfo.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.moyuaninfo.entity.MyyUserCron;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;
import com.moyuaninfo.service.MyyUserCronManger;

import java.util.Date;

/**
 * 定时器工具类
 *
 * @author 邱祥霸
 * @date 2020/4/8
 */
@Component
public class SchedulingUtils {

    @Autowired
    private MyyUserCronManger myyUserCronManger;

    public static void main(String[] args) {
    }

    /**
     * 获取下一次执行时间
     *
     * @param date: 时间
     * @return java.util.Date
     *
     * @author 邱祥霸
     * @date 2020/4/8
     */
    public Date getNextExecDate(Date date) {
        MyyUserCron myyUserCron = myyUserCronManger.findMyyUserCronByState();
        String cron = null != myyUserCron? myyUserCron.getCron() : null;
        if(StrUtil.isBlank(cron)) { return null; }

        CronTrigger trigger = new CronTrigger(cron);
        SimpleTriggerContext triggerContext = new SimpleTriggerContext();

        triggerContext.update(date, date, date);
        Date nextExecDate = trigger.nextExecutionTime(triggerContext);
        System.out.println(DateUtil.format(nextExecDate, "yyyy-MM-dd HH:mm:ss SSS"));

        return nextExecDate;
    }
}
